package com.kuanter.kuanterauto.main;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;

import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.constants.MainConstants;

/***
 * 更新版本
 * 
 * 
 */
@SuppressLint({ "HandlerLeak", "NewApi" })
public class UpdateService extends Service {
	private static final int TIMEOUT = 30 * 1000;// 超时
	// http://113.57.196.238:8080/App/resources/download/KuanterAuto.apk
	private static final String down_url = MainConstants.HOST_test
			+ "resources/download/KuanterAuto.apk";
	private static final int DOWN_OK = 1;
	private static final int DOWN_NUM = 2;
	private static final int DOWN_ERROR = 0;

	private String app_name="";

	private NotificationManager notificationManager;
	private Notification notification;

	private Intent updateIntent;
	private PendingIntent pendingIntent;

	private int notification_id = 0;
	
	DownLoadReceiver dReceiver;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	String size;
	@Override
	public void onCreate() {
		super.onCreate();
	}
	
	long d_id;
//	DownloadManager dm;

	@SuppressLint("NewApi")
	@Override
	public void onStart(Intent intent, int startId) {
		System.out.println("onStart");
//		if (null!=intent.getStringExtra("app_name")) {
			app_name = getResources().getString(R.string.app_name);

			// 创建文件
			FileUtil.createFile(app_name);

			createNotification();
			if(intent != null) {
				size = intent.getStringExtra("size");
				createThread(size);
			} else {
				if(notificationManager != null) {
					notificationManager.cancel(0);
				}
				stopSelf();
			}
			
			
			
			//--------------------
			/*if(android.os.Build.VERSION.SDK_INT >= 9) {
				dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
				DownloadManager.Request request = new DownloadManager.Request(Uri.parse(down_url));
				request.setDestinationUri(Uri.fromFile(FileUtil.updateFile));
				request.setTitle("宽途汽车更新");
				request.setAllowedNetworkTypes(Request.NETWORK_MOBILE|Request.NETWORK_WIFI);
				request.setDestinationInExternalPublicDir(FileUtil.updateDir.toString(), "test.apk");
				request.setShowRunningNotification(true);
				d_id = dm.enqueue(request);
				dReceiver = new DownLoadReceiver();
				registerReceiver(dReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
			}*/
			System.out.println("UpdateService");
			super.onStart(intent, startId);
//		}
	}

	/***
	 * 更新UI
	 */
	final Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Intent i= new Intent(getApplicationContext(), UpdateService.class);
			switch (msg.what) {
			case DOWN_OK:
				stopSelf();
				// 下载完成，点击安装
				Uri uri = Uri.fromFile(FileUtil.updateFile);
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(uri,
						"application/vnd.android.package-archive");

				pendingIntent = PendingIntent.getActivity(UpdateService.this,
						0, intent, 0);

				notification.setLatestEventInfo(UpdateService.this, app_name,
						"下载成功，点击安装", pendingIntent);

				notificationManager.notify(notification_id, notification);
				
				stopService(i);
//				stopService(updateIntent);
				break;
			case DOWN_ERROR:
				// notification.setLatestEventInfo(UpdateService.this, app_name,
				// "下载失败", pendingIntent);
				contentView.setTextViewText(R.id.notificationTitle,
						"网络出错，请检查网络!");
				contentView.setTextViewText(R.id.notificationPercent, 0 + "%");
				contentView.setProgressBar(R.id.notificationProgress, 100, 0,
						false);
				notificationManager.notify(notification_id, notification);
				stopService(i);
//				stopService(updateIntent);
				break;
			case DOWN_NUM:

				break;
			default:
				stopService(i);
				break;
			}

		}

	};

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		return super.onStartCommand(intent, flags, startId);

	}
	
	@Override
	public void onDestroy() {
		System.out.println("onDestroy");
		super.onDestroy();
	}

	/***
	 * 开线程下载
	 */
	public void createThread(final String size) {

		final Message message = new Message();

		new Thread(new Runnable() {
			@Override
			public void run() {

				try {
					long downloadSize = downloadUpdateFile(down_url,
							FileUtil.updateFile.toString(),size);
					if (downloadSize > 0) {
						// 下载成功
						message.what = DOWN_OK;
						handler.sendMessage(message);
					}

				} catch (Exception e) {
					message.what = DOWN_ERROR;
					handler.sendMessage(message);
					e.printStackTrace();
				}

			}
		}).start();
	}

	/***
	 * 创建通知栏
	 */
	RemoteViews contentView;

	public void createNotification() {
		notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		notification = new Notification(R.drawable.ic_launcher, "宽途汽车更新",
				System.currentTimeMillis());
		// notification.icon = R.drawable.ic_launcher;
		// // 这个参数是通知提示闪出来的值.
		// notification.tickerText = "开始下载";
		//
		// updateIntent = new Intent(this, MainActivity.class);
		// pendingIntent = PendingIntent.getActivity(this, 0, updateIntent, 0);
		//
		// // 这里面的参数是通知栏view显示的内容
		// notification.setLatestEventInfo(this, app_name, "下载：0%",
		// pendingIntent);
		//
		// notificationManager.notify(notification_id, notification);

		/***
		 * 在这里我们用自定的view来显示Notification
		 */
		contentView = new RemoteViews(getPackageName(),
				R.layout.notification_item);
		contentView.setTextViewText(R.id.notificationTitle, "正在下载宽途汽车");
		contentView.setTextViewText(R.id.notificationPercent, "0%");
		contentView.setProgressBar(R.id.notificationProgress, 100, 0, false);

		notification.contentView = contentView;

		// updateIntent = new Intent(this, MainActivity.class);
		updateIntent = new Intent();
//		updateIntent.addFlags(Intent.f);
		pendingIntent = PendingIntent.getActivity(this, 0, updateIntent,
				PendingIntent.FLAG_UPDATE_CURRENT);

		notification.contentIntent = pendingIntent;

		notificationManager.notify(notification_id, notification);

	}

	/***
	 * 下载文件
	 * 
	 * @return
	 * @throws MalformedURLException
	 */
	public long downloadUpdateFile(String down_url, String file,String size)
			throws Exception {
		long totalSize = 0l;// 文件总大小
		try {
			totalSize = Long.valueOf(size);
		} catch (Exception e) {
			
		}
		Message msg = new Message();
		msg.what = DOWN_NUM; 
		InputStream inputStream = null;
		OutputStream outputStream = null;
		int down_step = 5;// 提示step
		int downloadCount = 0;// 已经下载好的大小
		int updateCount = 0;// 已经上传的文件大小

		URL url = new URL(down_url);
		HttpURLConnection httpURLConnection = (HttpURLConnection) url
				.openConnection();
		httpURLConnection.setConnectTimeout(TIMEOUT);
		httpURLConnection.setReadTimeout(TIMEOUT);
		httpURLConnection.setRequestProperty("Accept-Encoding", "identity"); 
		httpURLConnection.connect();
//		int sizes = httpURLConnection.getContentLength();
		// 获取下载文件的size

		if (httpURLConnection.getResponseCode() == 200) {
			inputStream = httpURLConnection.getInputStream();
//			int sizes1 = httpURLConnection.getContentLength();
			// totalSize = httpURLConnection.getContentLength();
			// System.out.println("totalSize" + totalSize);
			if(totalSize == 0l) {
				totalSize = (long) (6.6 * 1024 * 1024l);  //TODO   .................TODO
			} else {
				totalSize = totalSize * 1024 * 1024;
			}
			outputStream = new FileOutputStream(file, false);// 文件存在则覆盖掉
			byte buffer[] = new byte[1024];
			int readsize = 0;
			while ((readsize = inputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, readsize);
				downloadCount += readsize;// 时时获取下载到的大小
				/**
				 * 每次增张5%
				 */
				if (updateCount == 0
						|| (downloadCount * 100 / totalSize - down_step) >= updateCount) {
					updateCount += down_step;
					// 改变通知栏
					// notification.setLatestEventInfo(this, "正在下载...",
					// updateCount
					// + "%" + "", pendingIntent);
					contentView.setTextViewText(R.id.notificationPercent,
							updateCount + "%");
					contentView.setProgressBar(R.id.notificationProgress, 100,
							updateCount, false);
					// show_view
					notificationManager.notify(notification_id, notification);
				}

			}

		}
		if (httpURLConnection != null) {
			httpURLConnection.disconnect();
		}
		inputStream.close();
		outputStream.close();

		return downloadCount;

	}

	class DownLoadReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			/*DownloadManager.Query query = new DownloadManager.Query(); 
			query.setFilterById(d_id);
			Cursor c = dm.query(query);
			if(c.moveToFirst()) {
				int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
				if(status == DownloadManager.STATUS_SUCCESSFUL) {
					
				}
			}*/
			Uri uri = Uri.fromFile(FileUtil.updateFile);
			Intent intent_d = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(uri,
					"application/vnd.android.package-archive");
			intent_d.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent_d);
		}
		
	}
}
